{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Statistics\n",
    "\n",
    "In Smile, there are many statistical functions to describe and analyze data. For example, use the following functions to calculate the descriptive statistics for your data: `sum`, `mean`, `median`, `q1`, `q3`, `variance`, `sd`, `mad` (median absolute deviation), `min`, `max`, `whichMin`, `whichMax`, etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import $ivy.`com.github.haifengl::smile-scala:4.0.0`\n",
    "import $ivy.`org.slf4j:slf4j-simple:2.0.16` \n",
    "\n",
    "import smile.math._\n",
    "import smile.math.MathEx.{log2, sigmoid, factorial, lfactorial, choose, lchoose, random, randomInt, permutate, c, cbind, rbind, sum, mean, median, q1, q3, `var` => variance, sd, mad, min, max, whichMin, whichMax, unique, dot, distance, pdist, pdot, KullbackLeiblerDivergence => kld, JensenShannonDivergence => jsd, cov, cor, spearman, kendall, norm, norm1, norm2, normInf, standardize, normalize, scale, unitize, unitize1, unitize2}\n",
    "import smile.stat._\n",
    "import smile.stat.distribution._"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "mean(Array(1.0, 2.0, 3.0, 4.0))\n",
    "\n",
    "sd(Array(1.0, 2.0, 3.0, 4.0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Distributions\n",
    "\n",
    "Probability distributions are theoretical distributions based on assumptions about a source population. The distributions assign probability to the event that a random variable has a specific, discrete value, or falls within a specified range of continuous values.\n",
    "\n",
    "All univariate distributions in Smile implements the interface `smile.math.stat.distribution.Distribution`. We support Bernoulli, beta, binomial, χ2, exponential, F, gamma, Gaussian, geometric, hyper geometric, logistic, log normal, negative binomial, Possion, shift geometric, t, and Weibull distribution. In additional, multivariate Gaussian distribution is supported. In fact, we also support finite mixture models and can estimate the exponential family mixture models from data.\n",
    "\n",
    "A `Distribution` object can be created with given parameters. Meanwhile they can be created by estimating parameters from a given data set. With a `Distribution` object, we may access its distribution parameter(s), mean, variance, standard deviation, entropy, generates a random number following the distribution, call its probability density function (the method p or cumulative distribution function (cdf). The reverse function of cdf is quantile. We can also calculate the likelihood or log likelihood of a sample set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val e = new ExponentialDistribution(1.0)\n",
    "\n",
    "e.mean\n",
    "\n",
    "e.variance\n",
    "\n",
    "e.sd\n",
    "\n",
    "e.entropy\n",
    "\n",
    "// generate a random number\n",
    "e.rand\n",
    "\n",
    "// PDF\n",
    "e.p(2.0)\n",
    "\n",
    "e.cdf(2.0)\n",
    "\n",
    "e.quantile(0.1)\n",
    "\n",
    "e.logLikelihood(Array(1.0, 1.1, 0.9, 1.5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The below example estimates a distribution from data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val e = ExponentialDistribution.fit(Array(1.0, 1.1, 0.9, 1.5, 1.8, 1.9, 2.0, 0.5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The below is a more advanced example of estimating a mixture model of Gaussian, exponential and gamma distribution. The result is quite accurate for this complicated case."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val gaussian = new GaussianDistribution(-2.0, 1.0)\n",
    "val exp = new ExponentialDistribution(0.8)\n",
    "val gamma = new GammaDistribution(2.0, 3.0)\n",
    "\n",
    "// generate the samples\n",
    "val data = Array.fill(500)(gaussian.rand()) ++ Array.fill(500)(exp.rand()) ++ Array.fill(1000)(gamma.rand())\n",
    "\n",
    "// define the initial guess of the components in the mixture model\n",
    "val a = new Mixture.Component(0.3, new GaussianDistribution(0.0, 1.0))\n",
    "val b = new Mixture.Component(0.3, new ExponentialDistribution(1.0))\n",
    "val c = new Mixture.Component(0.4, new GammaDistribution(1.0, 2.0))\n",
    "\n",
    "// estimate the model\n",
    "val mixture = ExponentialFamilyMixture.fit(data, a, b, c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If the distribution family is not known, nonparametric methods such as kernel density estimation can be used. Kernel density estimation is a fundamental data smoothing problem where inferences about the population are made, based on a finite data sample. It is also known as the Parzen window method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val k = new KernelDensity(data)\n",
    "\n",
    "k.p(1.0)\n",
    "\n",
    "mixture.p(1.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hypothesis Test\n",
    "\n",
    "A statistical hypothesis test is a method of making decisions using data, whether from a controlled experiment or an observational study (not controlled). In statistics, a result is called statistically significant if it is unlikely to have occurred by chance alone, according to a pre-determined threshold probability, the significance level."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### χ2 Test\n",
    "\n",
    "#### One-Sample Test\n",
    "\n",
    "Given the array x containing the observed numbers of events, and an array prob containing the expected probabilities of events, and given the number of constraints (normally one), a small value of p-value indicates a significant difference between the distributions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val bins = Array(20, 22, 13, 22, 10, 13)\n",
    "val prob = Array(1.0/6, 1.0/6, 1.0/6, 1.0/6, 1.0/6, 1.0/6)\n",
    "chisqtest(bins, prob)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Two-Sample Test\n",
    "\n",
    "Given the arrays x and y, containing two sets of binned data, and given one constraint, a small value of p-value indicates a significant difference between two distributions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val bins1 = Array(8, 13, 16, 10, 3)\n",
    "val bins2 = Array(4,  9, 14, 16, 7)\n",
    "chisqtest2(bins1, bins2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Independence Test\n",
    "\n",
    "Independence test on a two-dimensional contingency table in the form of an array of integers. The rows of contingency table are labels by the values of one nominal variable, the columns are labels by the values of the other nominal variable, and whose entries are non-negative integers giving the number of observed events for each combination of row and column. Continuity correction will be applied when computing the test statistic for 2x2 tables: one half is subtracted from all |O-E| differences. The correlation coefficient is calculated as Cramer's V."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(Array(12, 7), Array(5, 7))\n",
    "chisqtest(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### F Test\n",
    "\n",
    "Test if the arrays x and y have significantly different variances. Small values of p-value indicate that the two arrays have significantly different variances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(0.48074284, -0.52975023, 1.28590721, 0.63456079, -0.41761197, 2.76072411,\n",
    "            1.30321095, -1.16454533, 2.27210509, 1.46394553, -0.31713164, 1.26247543,\n",
    "            2.65886430, 0.40773450, 1.18055440, -0.39611251, 2.13557687, 0.40878860,\n",
    "            1.28461394, -0.02906355)\n",
    "\n",
    "val y = Array(1.7495879, 1.9359727, 3.1294928, 0.0861894, 2.1643415, 0.1913219,\n",
    "            -0.3947444, 1.6910837, 1.1548294, 0.2763955, 0.4794719, 3.1805501,\n",
    "            1.5700497, 2.6860190, -0.4410879, 1.8900183, 1.3422381, -0.1701592)\n",
    "\n",
    "ftest(x, y)\n",
    "\n",
    "val z = Array(0.6621329, 0.4688975, -0.1553013, 0.4564548, 2.2776146, 2.1543678,\n",
    "            2.8555142, 1.5852899, 0.9091290, 1.6060025, 1.0111968, 1.2479493,\n",
    "            0.9407034, 1.7167572, 0.5380608, 2.1290007, 1.8695506, 1.2139096)\n",
    "\n",
    "ftest(x, z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### t Test\n",
    "\n",
    "#### One-Sample Test\n",
    "Independent one-sample t-test whether the mean of a normally distributed population has a value specified in a null hypothesis. Small values of p-value indicate that the array has significantly different mean."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(0.48074284, -0.52975023, 1.28590721, 0.63456079, -0.41761197, 2.76072411,\n",
    "            1.30321095, -1.16454533, 2.27210509, 1.46394553, -0.31713164, 1.26247543,\n",
    "            2.65886430, 0.40773450, 1.18055440, -0.39611251, 2.13557687, 0.40878860,\n",
    "            1.28461394, -0.02906355)\n",
    "        \n",
    "ttest(x, 1.0)\n",
    "\n",
    "ttest(x, 1.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Paired Two-Sample Test\n",
    "Given the paired arrays x and y, test if they have significantly different means. Small values of p-value indicate that the two arrays have significantly different means."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val y = Array(1.7495879, 1.9359727, 3.1294928, 0.0861894, 2.1643415, 0.1913219,\n",
    "            -0.3947444, 1.6910837, 1.1548294, 0.2763955, 0.4794719, 3.1805501,\n",
    "            1.5700497, 2.6860190, -0.4410879, 1.8900183, 1.3422381, -0.1701592)\n",
    "\n",
    "val z = Array(0.6621329, 0.4688975, -0.1553013, 0.4564548, 2.2776146, 2.1543678,\n",
    "            2.8555142, 1.5852899, 0.9091290, 1.6060025, 1.0111968, 1.2479493,\n",
    "            0.9407034, 1.7167572, 0.5380608, 2.1290007, 1.8695506, 1.2139096)\n",
    "\n",
    "ttest(y, z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Independent (Unpaired) Two-Sample Test\n",
    "Test if the arrays x and y have significantly different means. Small values of p-value indicate that the two arrays have significantly different means. If the parameter equalVariance is true, the data arrays are assumed to be drawn from populations with the same true variance. Otherwise, The data arrays are allowed to be drawn from populations with unequal variances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(0.48074284, -0.52975023, 1.28590721, 0.63456079, -0.41761197, 2.76072411,\n",
    "            1.30321095, -1.16454533, 2.27210509, 1.46394553, -0.31713164, 1.26247543,\n",
    "            2.65886430, 0.40773450, 1.18055440, -0.39611251, 2.13557687, 0.40878860,\n",
    "            1.28461394, -0.02906355)\n",
    "\n",
    "val y = Array(1.7495879, 1.9359727, 3.1294928, 0.0861894, 2.1643415, 0.1913219,\n",
    "            -0.3947444, 1.6910837, 1.1548294, 0.2763955, 0.4794719, 3.1805501,\n",
    "            1.5700497, 2.6860190, -0.4410879, 1.8900183, 1.3422381, -0.1701592)\n",
    "\n",
    "ttest2(x, y)\n",
    "ttest2(x, y, true)\n",
    "\n",
    "val z = Array(0.6621329, 0.4688975, -0.1553013, 0.4564548, 2.2776146, 2.1543678,\n",
    "            2.8555142, 1.5852899, 0.9091290, 1.6060025, 1.0111968, 1.2479493,\n",
    "            0.9407034, 1.7167572, 0.5380608, 2.1290007, 1.8695506, 1.2139096)\n",
    "\n",
    "ttest2(x, z)\n",
    "ttest2(x, z, true)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Kolmogorov–Smirnov Test\n",
    "#### One-Sample Test\n",
    "The one-sample K-S test for the null hypothesis that the data set x is drawn from the given distribution. Small values of p-value show that the cumulative distribution function of x is significantly different from the given distribution. The array x is modified by being sorted into ascending order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(\n",
    "            0.53236606, -1.36750258, -1.47239199, -0.12517888, -1.24040594, 1.90357309,\n",
    "            -0.54429527, 2.22084140, -1.17209146, -0.68824211, -1.75068914, 0.48505896,\n",
    "            2.75342248, -0.90675303, -1.05971929, 0.49922388, -1.23214498, 0.79284888,\n",
    "            0.85309580, 0.17903487, 0.39894754, -0.52744720, 0.08516943, -1.93817962,\n",
    "            0.25042913, -0.56311389, -1.08608388, 0.11912253, 2.87961007, -0.72674865,\n",
    "            1.11510699, 0.39970074, 0.50060532, -0.82531807, 0.14715616, -0.96133601,\n",
    "            -0.95699473, -0.71471097, -0.50443258, 0.31690224, 0.04325009, 0.85316056,\n",
    "            0.83602606, 1.46678847, 0.46891827, 0.69968175, 0.97864326, 0.66985742,\n",
    "            -0.20922486, -0.15265994)\n",
    "\n",
    "kstest(x, new GaussianDistribution(0, 1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Two-Sample Test\n",
    "The two-sample K–S for the null hypothesis that the data sets are drawn from the same distribution. Small values of p-value show that the cumulative distribution function of x is significantly different from that of y. The arrays x and y are modified by being sorted into ascending order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(\n",
    "            0.53236606, -1.36750258, -1.47239199, -0.12517888, -1.24040594, 1.90357309,\n",
    "            -0.54429527, 2.22084140, -1.17209146, -0.68824211, -1.75068914, 0.48505896,\n",
    "            2.75342248, -0.90675303, -1.05971929, 0.49922388, -1.23214498, 0.79284888,\n",
    "            0.85309580, 0.17903487, 0.39894754, -0.52744720, 0.08516943, -1.93817962,\n",
    "            0.25042913, -0.56311389, -1.08608388, 0.11912253, 2.87961007, -0.72674865,\n",
    "            1.11510699, 0.39970074, 0.50060532, -0.82531807, 0.14715616, -0.96133601,\n",
    "            -0.95699473, -0.71471097, -0.50443258, 0.31690224, 0.04325009, 0.85316056,\n",
    "            0.83602606, 1.46678847, 0.46891827, 0.69968175, 0.97864326, 0.66985742,\n",
    "            -0.20922486, -0.15265994)\n",
    "val y = Array(\n",
    "            0.95791391, 0.16203847, 0.56622013, 0.39252941, 0.99126354, 0.65639108,\n",
    "            0.07903248, 0.84124582, 0.76718719, 0.80756577, 0.12263981, 0.84733360,\n",
    "            0.85190907, 0.77896244, 0.84915723, 0.78225903, 0.95788055, 0.01849366,\n",
    "            0.21000365, 0.97951772, 0.60078520, 0.80534223, 0.77144013, 0.28495121,\n",
    "            0.41300867, 0.51547517, 0.78775718, 0.07564151, 0.82871088, 0.83988694)\n",
    "\n",
    "kstest(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Correlation Test\n",
    "#### Pearson Correlation\n",
    "The t-test is used to establish if the correlation coefficient is significantly different from zero, and, hence that there is evidence of an association between the two variables. There is then the underlying assumption that the data is from a normal distribution sampled randomly. If this is not true, then it is better to use Spearman's coefficient of rank correlation (for non-parametric variables)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "val x = Array(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)\n",
    "val y  = Array(2.6,  3.1,  2.5,  5.0,  3.6,  4.0,  5.2,  2.8,  3.8)\n",
    "\n",
    "pearsontest(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Spearman Rank Correlation\n",
    "The Spearman Rank Correlation Coefficient is a form of the Pearson coefficient with the data converted to rankings (i.e. when variables are ordinal). It can be used when there is non-parametric data and hence Pearson cannot be used.\n",
    "\n",
    "The raw scores are converted to ranks and the differences between the ranks of each observation on the two variables are calculated.\n",
    "\n",
    "The p-value is calculated by approximation, which is good for n > 10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "spearmantest(x, y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Kendall Rank Correlation\n",
    "The Kendall Tau Rank Correlation Coefficient is used to measure the degree of correspondence between sets of rankings where the measures are not equidistant. It is used with non-parametric data. The p-value is calculated by approximation, which is good for n > 10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "kendalltest(x, y)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Scala (2.13)",
   "language": "scala",
   "name": "scala213"
  },
  "language_info": {
   "codemirror_mode": "text/x-scala",
   "file_extension": ".sc",
   "mimetype": "text/x-scala",
   "name": "scala",
   "nbconvert_exporter": "script",
   "version": "2.13.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
